export function hasClass(el, className) {
    let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
    return reg.test(el.className)
}

export function addClass(el, className) {
    if (hasClass(el, className)) {
        return
    }

    let newClass = el.className.split(' ')
    newClass.push(className)
    el.className = newClass.join(' ')
}

export function getData(el, name, val) {
    const prefix = 'data-'
    if (val) {
        return el.setAttribute(prefix + name, val)
    }
    return el.getAttribute(prefix + name)
}

let elementStyle = document.createElement('div').style

let vendor = (() => {
    let transformNames = {
        webkit: 'webkitTransform',
        Moz: 'MozTransform',
        O: 'OTransform',
        ms: 'msTransform',
        standard: 'transform'
    }

    for (let key in transformNames) {
        if (elementStyle[transformNames[key]] !== undefined) {
            return key
        }
    }

    return false
})()

export function prefixStyle(style) {
    if (vendor === false) {
        return false
    }

    if (vendor === 'standard') {
        return style
    }

    return vendor + style.charAt(0).toUpperCase() + style.substr(1)
}

export function getParents(el, target) {
    let matched = []
    let truncate = target !== undefined
    // nodeType == 9，表示Document
    // 当元素存在，并且元素不是Document
    while ((el = el.parentNode) && el.nodeType !== 9) {
        // nodeType == 1，表示节点为元素
        if (el.nodeType === 1) {
            // 如果存在搜索终点（标签名|类名），退出查找
            if (truncate) {
                if (el.nodeName.toLowerCase() === target || el.className.indexOf(target.substring(1)) > -1) {
                    matched.push(el)
                }
            }
        }
    }
    return matched
}

export function getCss(o, key) {
    return o.currentStyle ? o.currentStyle[key] : document.defaultView.getComputedStyle(o, false)[key]
}

export function getSiblings(target) {
    let parentEl = target.parentNode
    let childs = parentEl.children
    let siblings = []
    for (let i = 0; i <= childs.length - 1; i++) {
        if (childs[i] === target) {
            continue
        }
        siblings[siblings.length] = childs[i]
    }
    return siblings
}
